算是檢驗自己對JavaScript理解一個很好的方法:
範例 :
const cat1 = {
name:"咪咪",
age:2,
color:"白色"
}
const cat2 = {
name:"妹妹",
age:1,
color:"虎斑"
}
const cat3 = {
name:"Toby",
age:2,
color:"虎斑"
}
const cats = [cat1,cat2,cat3]
Array.prototype.ownForEach = function(callback) {
for(let i = 0; i < this.length; i++) {
callback(this[i],i,this)
}
}
cats.ownForEach((cat) => {
console.log(cat)
})
//
{name: "咪咪", age: 2, color: "白色"}
{name: "妹妹", age: 1, color: "虎斑"}
{name: "Toby", age: 2, color: "虎斑"}
Array.prototype.ownMap = function(callback) {
const result = [];
for(let i = 0; i < this.length; i++) {
result.push(callback(this[i],i,this))
}
return result;
}
console.log(cats.ownMap((item) => `一隻${item.color}的貓`))
// ["一隻白色的貓", "一隻虎斑的貓", "一隻虎斑的貓"]
Array.prototype.ownFilter = function(callback) {
const result = [];
for(let i = 0; i < this.length; i++) {
if(callback(this[i],i,this)) {
result.push(this[i]);
}
}
return result;
}
console.log(cats.ownFilter((item) => item.color == '虎斑'))
//
0: {name: "妹妹", age: 1, color: "虎斑"}
1: {name: "Toby", age: 2, color: "虎斑"}
這邊有另外一個寫法 :
Array.prototype.ownFilter = function(callback) {
const result = [];
for(let i = 0; i < this.length; i++) {
callback(this[i],i,this) && result.push(this[i]) // 前者true就會執行後者
}
return result;
}
Array.prototype.ownEvery = function(callback) {
let isAllTrue = true;
for(let i = 0; i < this.length; i++) {
isAllTrue = callback(this[i],i,this);
if(!isAllTrue) break;
}
return isAllTrue;
}
console.log(cats.ownEvery((item) => item.age === 1)); // false
Array.prototype.ownSome = function(callback) {
let isTrue = false
for(let i = 0; i < this.length; i++) {
isTrue = callback(this[i],i,this);
if(isTrue) break
}
return isTrue;
}
console.log(cats.ownSome((item) => item.color === '黑色')); //false
Array.prototype.ownReduce = function(callback, initValue) {
let startIndex = 0;
let pre;
if(initValue || initValue===0) {
pre = initValue
} else {
pre = this[0];
startIndex = 1;
}
for(let i = startIndex; i < this.length; i++) {
pre = callback(pre, this[i], this)
}
return pre
}
const ageTotal = cats.ownReduce((pre,cur) => pre + cur.age,0);
console.log(ageTotal); // 5